package definite.Guide.Book.JPopupMenu;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Popup;
import javax.swing.PopupFactory;
import javax.swing.Timer;

public class ButtonPopupSample {

	static ArrayList<Popup> list = new ArrayList<>();
	static final Random random = new Random();

	static class ButtonPopupActionListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			System.out.println("Selected : " + e.getActionCommand());
		}

	}

	static class PopupActionListener implements ActionListener {

		private Component component;

		public PopupActionListener(Component comp) {
			component = comp;
		}

		@Override
		public synchronized void actionPerformed(ActionEvent e) {
			JButton button = new JButton("Hello World");
			ActionListener listener = new ButtonPopupActionListener();
			button.addActionListener(listener);
			int x = random.nextInt(component.getWidth());
			int y = random.nextInt(component.getHeight());
			PopupFactory factory = new PopupFactory();
			final Popup popup = factory.getPopup(component, button, x, y);
			list.add(popup);
			popup.show();
			ActionListener action = new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					popup.hide();
				}
			};

			Timer t = new Timer(3000, action);
			t.start();
		}

	}

	public static void main(String[] args) {
		Runnable runner = new Runnable() {

			@Override
			public void run() {
				JFrame.setDefaultLookAndFeelDecorated(true);
				JFrame frame = new JFrame("Popup Demonstration");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				ActionListener listener = new PopupActionListener(frame);
				JButton btn = new JButton("Pick me for Popup");
				btn.addActionListener(listener);

				// my code
				JButton show = new JButton("Show Hide Popup");
				show.addActionListener(new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						for (int i = 0; i < list.size(); i++)
							list.get(i).show();
					}
				});

				// end my code -> but it not run !!!!! :(((((

				frame.setLayout(new BorderLayout());
				frame.add(btn, BorderLayout.CENTER);
				frame.add(show, BorderLayout.SOUTH);
				frame.setSize(450, 350);
				frame.setLocationRelativeTo(null);
				frame.setVisible(true);
			}
		};

		EventQueue.invokeLater(runner);
	}

}
